package com.example.demo.controller;


import com.example.demo.commen.Result;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserService;
import com.example.demo.utils.JavaUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private JavaUtils javaUtils;
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(UserInfo userInfo,HttpServletRequest request){
     if(userInfo==null){
         return null;
     }
     if(userInfo.getUserName()==null||userInfo.getPassword()==null){
         return null;
     }
        System.out.println("1234");
     UserInfo userInfo1 = userService.selectByName(userInfo.getUserName());
        Map<String,Object> map = new HashMap<>();
        map.put("id",userInfo1.getId());
        map.put("userName",userInfo1.getUserName());
        String token = JavaUtils.genJwt(map);
        System.out.println(token);
        HttpSession session = request.getSession(true);
        session.setAttribute("user",userInfo);

        return Result.success(token);
    }

   @RequestMapping("/getUserInfo")
    public Result  getUserInfo(HttpServletRequest request) {
       System.out.println("11111111");

        String token = request.getHeader("user_token");
      Integer id =  JavaUtils.getUserIdFromToken(token);

        System.out.println(id);
       UserInfo userInfo= userService.selectById(id);
        System.out.println("dadadadxxxxxx");
        System.out.println(userInfo.getUserName());
       System.out.println(userInfo.toString());
        return Result.success(userInfo);
    }


}
